<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="证书名称" prop="crtName">
        <el-input
          v-model="queryParams.crtName"
          placeholder="请输入证书名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lbconfig:proxyCrt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lbconfig:proxyCrt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lbconfig:proxyCrt:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="proxyCrtList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标识ID" align="center" prop="id" />
      <el-table-column label="证书名称" align="center" prop="crtName" />
      <el-table-column label="生成方式" align="center" prop="createType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crt_create_type" :value="scope.row.createType"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['lbconfig:proxyCrt:export']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lbconfig:proxyCrt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lbconfig:proxyCrt:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代理证书对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="证书名称" prop="crtName">
              <el-input v-model="form.crtName" placeholder="请输入证书名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="生成方式" prop="createType">
              <el-radio-group v-model="form.createType">
                <el-radio
                  v-for="dict in dict.type.crt_create_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="密钥位数" prop="sslKeyByte" v-if="form.createType == 'create'">
              <!-- <el-input v-model="form.sslKeyByte" placeholder="请输入密钥位数" /> -->
              <el-select v-model="form.sslKeyByte" placeholder="sslKeyByte">
                <el-option
                v-for="item in keyByteOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
          <el-form-item label="国家码" prop="sslCountry" v-if="form.createType == 'create'">
            <el-input v-model="form.sslCountry" maxlength="2" placeholder="请输入国家码" />
          </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
          <el-form-item label="省份" prop="sslProvince" v-if="form.createType == 'create'">
            <el-input v-model="form.sslProvince" maxlength="20" placeholder="请输入省份" />
          </el-form-item>
          </el-col>
          
          <el-col :span="12">
          <el-form-item label="城市" prop="sslCity" v-if="form.createType == 'create'">
            <el-input v-model="form.sslCity" maxlength="20" placeholder="请输入城市" />
          </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
        <el-col :span="12">
          <el-form-item label="组织" prop="sslOrganization" v-if="form.createType == 'create'">
            <el-input v-model="form.sslOrganization" maxlength="20" placeholder="请输入组织" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="组织单元" prop="sslUnit" v-if="form.createType == 'create'">
            <el-input v-model="form.sslUnit" maxlength="20" placeholder="请输入组织单元" />
          </el-form-item>
        </el-col>
        </el-row>
        
        <el-row>
        <el-col :span="12">
          <el-form-item prop="sslCommon" v-if="form.createType == 'create'">
            <span slot="label">
              通用名称
              <el-tooltip placement="right" effect="light">
                <div slot="content">代理服务域名或IP地址，如：<br>域名：domain.yourhost.com <br>绑定IP：192.168.100.100</div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="form.sslCommon" maxlength="20" placeholder="请输入通用名称" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="邮箱" prop="sslEmail" v-if="form.createType == 'create'">
            <el-input v-model="form.sslEmail" maxlength="60" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        </el-row>
        
        <el-row>
        <el-col :span="12">
          <el-form-item prop="sslPassword" v-if="form.createType == 'create'">
            <span slot="label">
              加密密码
              <el-tooltip content="加密密钥内容" placement="right" effect="light">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="form.sslPassword" :maxlength="16" placeholder="请输入密码" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12" v-if="form.createType == 'create'">
          <el-form-item prop="altIpAddress1" v-if="form.createType == 'create'">
            <span slot="label">
              扩展IP Address
              <el-tooltip placement="right" effect="light">
                <div slot="content">可选扩展IP Address，如：<br>绑定IP：192.168.100.100</div>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="form.altIpAddress1" placeholder="请输入扩展IP Address" />
          </el-form-item>
        </el-col>
        </el-row>

        <el-row>
        <el-col :span="24">
          <el-form-item prop="pemContent" v-if="form.createType == 'upload'">
          <span slot="label">
            证书内容
            <el-tooltip placement="right" effect="light">
              <div slot="content">作为服务端使用的证书，<br>包含了密钥部分和签名证书部分，<br>请提供正确的内容，<br>否则将导致代理启动失败。</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
            <el-input v-model="form.pemContent" type="textarea" rows="10" 
            placeholder="
示例内容：
-----BEGIN RSA PRIVATE KEY-----
......密钥部分......
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
......签名证书部分......
-----END CERTIFICATE-----" 
            />
          </el-form-item>
        </el-col>
        </el-row>
        
        <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProxyCrt, getProxyCrt, delProxyCrt, addProxyCrt, updateProxyCrt } from "@/api/lbconfig/proxyCrt";
import { isIPv4 } from "@/api/snowfieldValidate";

export default {
  name: "ProxyCrt",
  dicts: ['crt_create_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理证书表格数据
      proxyCrtList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        crtName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        crtName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        createType: [
          { required: true, message: "请选择生成方式", trigger: "change" }
        ],
        pemContent: [
          { required: true, message: "证书内容不能为空", trigger: "blur" }
        ],
        sslKeyByte: [
          { required: true, message: "请选择密钥位数", trigger: "change" }
        ],
        sslCountry: [
          { required: true, message: "国家码不能为空", trigger: "blur" },
          { min: 2, max: 2, message: "长度为 2 个字符", trigger: "blur" },
          { pattern: /^[^ ]+$/, message: "不能包含非法字符：空格", trigger: "blur" }
        ],
        sslProvince: [
          { required: true, message: "省份不能为空", trigger: "blur" },
          { max: 20, message: "长度最大为 20 个字符", trigger: "blur" },
          { pattern: /^[^ ]+$/, message: "不能包含非法字符：空格", trigger: "blur" }
        ],
        sslCity: [
          { required: true, message: "城市不能为空", trigger: "blur" },
          { max: 20, message: "长度最大为 20 个字符", trigger: "blur" },
          { pattern: /^[^ ]+$/, message: "不能包含非法字符：空格", trigger: "blur" }
        ],
        sslOrganization: [
          { required: true, message: "组织不能为空", trigger: "blur" },
          { max: 20, message: "长度最大为 20 个字符", trigger: "blur" },
          { pattern: /^[^ ]+$/, message: "不能包含非法字符：空格", trigger: "blur" }
        ],
        sslUnit: [
          { required: true, message: "组织单元不能为空", trigger: "blur" },
          { max: 20, message: "长度最大为 20 个字符", trigger: "blur" },
          { pattern: /^[^ ]+$/, message: "不能包含非法字符：空格", trigger: "blur" }
        ],
        sslCommon: [
          { required: true, message: "通用名称不能为空", trigger: "blur" },
          { max: 20, message: "长度最大为 20 个字符", trigger: "blur" },
          { pattern: /^[^ ]+$/, message: "不能包含非法字符：空格", trigger: "blur" }
        ],
        sslEmail: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          // { pattern: /^[^ ]+$/, message: "不能包含非法字符：空格", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
        ],
        sslPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 4, max: 16, message: "长度在 4 到 16 个字符", trigger: "blur" },
          { pattern: /^[^<>"'|\\ ]+$/, message: "不能包含非法字符：< > \" ' \\\ | 空格", trigger: "blur" }
        ],
        sslCompany: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        altIpAddress1: [
          { required: false, message: "扩展IP Address不能为空", trigger: "blur" },
          { validator:(rule,value,callback)=>{
            if(value != null && value != "" && !isIPv4(value)){
              callback(new Error("扩展IP Address格式有误"));
              return;
            }

            callback();
          }, message: "扩展IP Address格式有误", trigger: 'blur'},
        ],
      },
      // keybyte选项信息
      keyByteOptions: [{value:1024,label:"1024"},{value:2048,label:"2048"},{value:3072,label:"3072"},{value:4096,label:"4096"}]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询代理证书列表 */
    getList() {
      this.loading = true;
      listProxyCrt(this.queryParams).then(response => {
        this.proxyCrtList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.proxyCrtList);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        crtName: null,
        crtPath: null,
        createType: "upload",
        sslKeyByte: 4096,
        sslCountry: null,
        sslProvince: null,
        sslCity: null,
        sslOrganization: null,
        sslUnit: null,
        sslCommon: null,
        sslEmail: null,
        sslPassword: null,
        sslCompany: null,
        altIpAddress1: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        pemContent: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代理证书";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProxyCrt(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改代理证书";
      });
    },
    /** 下载证书操作 */
    handleDownload(row){
      const id = row.id || this.ids
      if(row.crtPath == "0"){
        this.$modal.msgError("证书文件不存在，请核查");
        return;
      } else {
        let fileName = row.crtName + ".pem";
        // console.log(fileName);
        this.download('lbconfig/proxyCrt/downloadCrt/'+id, {}, fileName)
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProxyCrt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProxyCrt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除代理证书编号为"' + ids + '"的数据项？').then(function() {
        return delProxyCrt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>
